<template>
  <div class="p-5">
    <div class="card-box box mt-5">
      <a-button type="primary" @click="addNewItem">新增主项</a-button>

      <a-form :model="formData">
        <a-table :columns="columns" :data-source="servlist" class="components-table-demo-nested" rowKey="id"
          :pagination="false" :defaultExpandAllRows="true">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'categoryId'">
              <a-form-item :name="`servlist[${index}].categoryId`">
                <a-select v-model:value="record.categoryId" style="width: 120px" :options="comclasslist"
                  placeholder="请选择"></a-select>
              </a-form-item>
            </template>
            <template v-if="column.key === 'weightGram'">
              <a-form-item :name="`servlist[${index}].weightGram`">
                <a-input-number v-model:value="record.weightGram" :disabled="!record.deleteflag" addon-after="g"
                  placeholder="请输入"></a-input-number>
              </a-form-item>
            </template>
            <template v-if="column.key === 'edibleSectionGram'">
              <a-form-item :name="`servlist[${index}].edibleSectionGram`">
                <a-input-number v-model:value="record.edibleSectionGram" addon-after="g"
                  placeholder="请输入"></a-input-number>
              </a-form-item>
            </template>

            <template v-if="column.key === 'action'">
              <a-button type="link" @click="addComponent(record)">新增成分</a-button>
              <a-button v-if="record.deleteflag" type="link" danger @click="deleteItem(index)">
                删除
              </a-button>
            </template>
          </template>

          <template #expandedRowRender="{ record, index: parentIndex }">
            <a-table :columns="columns2" :data-source="record.items" class="components-table-demo-nested custom-table"
              :pagination="false" rowKey="key">
              <template #bodyCell="{ column, record: subRecord, index: subIndex }">
                <template v-if="column.key === 'nutrientId'">
                  <a-form-item :name="`servlist[${parentIndex}].items[${subIndex}].nutrientId`">
                    <a-select v-model:value="subRecord.nutrientId" style="width: 120px"
                      :field-names="{ label: 'name', value: 'id' }" :options="newdata.nutrlist"
                      placeholder="请选择"></a-select>
                  </a-form-item>
                </template>
                <template v-if="column.key === 'amount'">
                  <a-form-item :name="`servlist[${parentIndex}].items[${subIndex}].amount`">
                    <!-- <a-input-number v-model:value="subRecord.amount" addon-after="g" placeholder="请输入"></a-input-number> -->
                    <a-input-number v-model:value="subRecord.amount" placeholder="请输入"></a-input-number>
                  </a-form-item>
                </template>

                <template v-if="column.key === 'action'">
                  <a-button type="link" danger @click="deleteComponent(record.items, subIndex)">
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </a-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, watch, ref, nextTick } from 'vue';
import { getcomlist } from "#/hooks/common.ts";
import * as api from '#/api/core/nutrition.ts'

// 定义 props 和 emit
const props = defineProps({
  value: {
    type: Array,
    default: () => [] // 提供默认值，避免 undefined
  },

  type: {
    type: String,
    default: 'add'
  }
})

const emits = defineEmits(['update:value'])

// 用 reactive 存储主数据（替代计算属性，更适合直接修改）
const flaga = ref(true)
const servlist = ref([
  {
    id: 1,
    categoryId: '',
    weightGram: 100,
    edibleSectionGram: null,
    deleteflag: false,
    items: [{
      key: '1-1',
      nutrientId: '',
      amount: null,
      nutrientCode: ''
    }]
  },
])


watch(
  () => props.value,
  async (newVal) => {
    if (props.type == 'update') {
      console.log('11', newVal, servlist);

      if (!flaga.value) {
        servlist.value = newVal.map(e => {
          return {
            ...e,
            items: e.nutrients
          }

        })


        await nextTick()
        flaga.value = true
        // flaga.value = true
      }

    }

  },
  { deep: true }
)


// 监听 servlist 变化，同步到父组件
watch(
  () => servlist,
  (newVal) => {

    console.log('监听111111111111', flaga.value, newVal);

    // 仅传递需要给父组件的数据（过滤内部临时字段如 key）
    // const emitData = newVal.map(item =>

    //   item.items.map(sub => ({
    //     nutrientId: sub.nutrientId,
    //     amount: sub.amount,
    //     nutrientCode: sub.nutrientCode,
    //   }))
    // )

    if (flaga.value) {
      const emitData = newVal.value.map((item) => {

        return {
          // ...item,
          categoryId: item.categoryId,
          edibleSectionGram: item.edibleSectionGram,
          weightGram: item.weightGram,
          items: item.items.map((e) => {
            return {
              amount: e.amount,
              nutrientId: e.nutrientId,
              nutrientCode: e.nutrientId ? newdata.nutrlist.find(i => {
                return i.id == e.nutrientId
              })?.code : null
            }
          })
        }
      })
      emits('update:value', emitData)

    }


  },
  { deep: true, flush: true } // 深度监听对象/数组变化
)

// 表格列配置
const columns = [
  {
    title: '份量单位',
    dataIndex: 'categoryId',
    key: 'categoryId',
    align: "center",
  },
  {
    title: '克数',
    dataIndex: 'weightGram',
    key: 'weightGram',
    align: "center",
  },
  {
    title: '可食用部分克数',
    dataIndex: 'edibleSectionGram',
    key: 'edibleSectionGram',
    align: "center",
  },
  {
    title: '操作',
    key: 'action',
    align: "center",
  },
];

const columns2 = [
  {
    title: '营养成分',
    dataIndex: 'nutrientId',
    key: 'nutrientId',
    align: "center",
  },
  {
    title: '数值',
    dataIndex: 'amount',
    key: 'amount',
    align: "center",
  },
  {
    title: '操作',
    key: 'action',
    align: "center",
  },
];

// 响应式数据存储
const newdata = reactive({
  nutrlist: [],
});

// 获取分类列表
const { comclasslist } = getcomlist(9);

// 获取营养成分列表
const getnutr = async () => {
  try {
    const temp = await api.$getlist()
    newdata.nutrlist = temp || [] // 处理空数据
    console.log('营养成分列表', temp);
  } catch (err) {
    console.error('获取营养成分失败', err)
  }
}
getnutr()

// 新增主项
const addNewItem = () => {
  const newId = servlist.value.length + 1;
  servlist.value.push({
    id: newId,
    categoryId: '',
    weightGram: null,
    edibleSectionGram: null,
    deleteflag: true,
    items: [{
      key: `${newId}-1`,
      nutrientId: '',
      amount: null,
      nutrientCode: ''
    }]
  });
};

// 删除主项
const deleteItem = (index) => {
  servlist.value.splice(index, 1);
  // 重新生成 id 避免重复（可选，根据需求）
  servlist.value.forEach((item, i) => item.id = i + 1);
};

// 新增成分
const addComponent = (record) => {
  const newKey = `${record.id}-${record.items.length + 1}`;
  record.items.push({
    key: newKey,
    nutrientId: '',
    amount: null,
    nutrientCode: ''
  });
};



// 删除成分
const deleteComponent = (items, index) => {
  items.splice(index, 1);
};

// 表单模型（与 a-form 绑定，用于表单验证）
const formData = reactive({
  servlist
})
</script>
<style scoped>
.custom-table {
  --header-bg-color: #f0f2f5;
  /* 表头背景色（浅灰，可自定义） */
  --header-text-color: #1890ff;
  /* 表头文字色（蓝色，可自定义） */
}

/* 覆盖 Ant Design 表格表头样式 */
.custom-table /deep/ .ant-table-thead>tr>th {
  background-color: var(--header-bg-color) !important;
  /* 表头背景 */
  color: var(--header-text-color) !important;
  /* 表头文字颜色 */
  font-weight: 600;
  /* 文字加粗（可选） */
}

/* 展开行的子表格表头样式（如果需要与主表格一致） */
.custom-table /deep/ .ant-table-thead>tr>th.ant-table-column-has-actions {
  background-color: var(--header-bg-color) !important;
}
</style>
